package Server.controller;

import Plug.operLog.OperLog;
import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.*;
import Server.entity.*;
import Server.tool.BeanToJson;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("ShopController")
public class ShopController {
    @Autowired
    private ShopActivityDao shopActivityDao;
    @Autowired
    private ShopClassDao shopClassDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private ShopSpecDao shopSpecDao;
    @Autowired
    private CityShopDao cityShopDao;
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private InviteUsersDao inviteUsersDao;
    @Autowired
    private UsersCityDao usersCityDao;
    @Autowired
    private CityDao cityDao;

    @RequestMapping("ActiveList")
    public RetResult List(@RequestBody JSONObject jsonObject){
        ShopActivity entity = (ShopActivity) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), ShopActivity.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<ShopActivity> example = Example.of(entity,matcher);
        Page<ShopActivity> userlist = shopActivityDao.findAll(example,pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    @RequestMapping("ClassList")
    public RetResult ClassList(@RequestBody JSONObject jsonObject){
        ShopClass entity = (ShopClass) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), ShopClass.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<ShopClass> example = Example.of(entity,matcher);
        Page<ShopClass> userlist = shopClassDao.findAll(example,pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    @RequestMapping("SpecList")
    public RetResult SpecList(@RequestBody JSONObject jsonObject){
        ShopSpec entity = (ShopSpec) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), ShopSpec.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<ShopSpec> example = Example.of(entity,matcher);
        Page<ShopSpec> userlist = shopSpecDao.findAll(example,pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    @RequestMapping("SpecCityList")
    public RetResult SpecCityList(@RequestBody JSONObject jsonObject){
        CityShop entity = (CityShop) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), CityShop.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "uuid");
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<CityShop> example = Example.of(entity,matcher);
        Page<CityShop> userlist = cityShopDao.findAll(example,pageable);
        return RetResponse.makeRsp(0, "成功", userlist.getContent(), (int) userlist.getTotalElements());
    }
    @OperLog("分类修改保存")
    @RequestMapping("ClassSave")
    public RetResult ClassSave(@RequestBody ShopClass shopClass){
        if(StringUtils.isEmpty(shopClass.getUuid())){
            shopClass.setStatus(ShopClass.Status.ING);
            shopClassDao.save(shopClass);
        }else{
            if(shopClass.getStatus()==null){
                ShopClass entity = shopClassDao.findByUuid(shopClass.getUuid());
                shopClass.setStatus(entity.getStatus());
            }
            shopClassDao.save(shopClass);
        }
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("GetClass")
    public RetResult GetClass(@RequestBody ShopClass shopClass){
        return RetResponse.makeOKRsp(shopClassDao.findByUuid(shopClass.getUuid()));
    }
    @OperLog("分类禁用开启")
    @RequestMapping("ClassDel")
    public RetResult ClassDel(@RequestBody ShopClass shopClass){
        shopClass=shopClassDao.findByUuid(shopClass.getUuid());
        if(shopClass.getStatus().equals(ShopClass.Status.ING)){
            shopClass.setStatus(ShopClass.Status.NO);
        }else{
            shopClass.setStatus(ShopClass.Status.ING);
        }
        shopClassDao.save(shopClass);
        return RetResponse.makeOKRsp();
    }


    @OperLog("活动修改保存")
    @RequestMapping("ActiveSave")
    public RetResult ActiveSave(@RequestBody ShopActivity shopActivity){
        if(StringUtils.isEmpty(shopActivity.getUuid())){
            shopActivity.setStatus(ShopActivity.Status.ING);
            shopActivityDao.save(shopActivity);
        }else{
            shopActivityDao.save(shopActivity);
        }
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("GetActive")
    public RetResult GetActive(@RequestBody ShopActivity shopActivity){
        return RetResponse.makeOKRsp(shopActivityDao.findByUuid(shopActivity.getUuid()));
    }
    @OperLog("活动过期")
    @RequestMapping("ActiveDel")
    public RetResult ActiveDel(@RequestBody ShopActivity shopActivity){
        shopActivity=shopActivityDao.findByUuid(shopActivity.getUuid());
        shopActivity.setStatus(ShopActivity.Status.NO);
        shopActivityDao.save(shopActivity);
        return RetResponse.makeOKRsp();
    }
    @Autowired
    EntityManager entityManager;
    @OperLog("商品增加")
    @RequestMapping("AddShop")
    @Transactional
    public RetResult AddShop(@RequestBody JSONObject jsonObject){
        Shop shop =(Shop) BeanToJson.jsonTobean(jsonObject.getJSONObject("shop").toString(),Shop.class);
        shop.setStatus(Shop.Status.ING);
        try {
            shop=shopDao.save(shop);
            JSONArray jsonArray = jsonObject.getJSONArray("spec");
            List<String> uid=new LinkedList<>();
            for (Object obj : jsonArray) {
                JSONObject jso = (JSONObject) obj;
                ShopSpec stage = (ShopSpec) BeanToJson.jsonTobean(jso.toString(), ShopSpec.class);
                if(StringUtils.isEmpty(stage.getUuid())){
                    stage.setShop(shop);
                    stage.setStatus(ShopSpec.Status.ING);
                    stage=shopSpecDao.save(stage);
                    uid.add(stage.getUuid());
                }else{
                    stage.setShop(shop);
                    stage.setStatus(ShopSpec.Status.ING);
                    uid.add(stage.getUuid());
                    shopSpecDao.save(stage);
                }

            }
            entityManager.createNativeQuery("update shop_spec set status='NO' where shop_id = '"+shop.getUuid()+"' and uuid not in ('"+StringUtils.join(uid.toArray(),"','")+"')").executeUpdate();
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return RetResponse.makeErrRsp("失败");
        }
        return RetResponse.makeOKRsp();
    }

    @RequestMapping("GetShop")
    public RetResult GetShop(@RequestBody Shop shop){
        shop=shopDao.findByUuid(shop.getUuid());
        List<ShopSpec> specs  = shopSpecDao.findByShopAndStatus(shop,ShopSpec.Status.ING);
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        if(fspuser!=null){
            fspuser = usersDao.findByUuid(fspuser.getUuid());
            if(fspuser.getType().equals(Users.Type.USER)){
                for(ShopSpec sp:specs){
                    CityShop cityShop = cityShopDao.findByShopSpecAndCity(sp,cityDao.findByCityLike(fspuser.getAddress()));
                    if(cityShop!=null){
                        sp.setPrice(cityShop.getMoney());
                    }
                }
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("shop",shop);
        map.put("spec",specs);
        return RetResponse.makeOKRsp(map);
    }

    @OperLog("商品删除")
    @RequestMapping("DelShop")
    public RetResult DelShop(@RequestBody Shop shop){
        shop=shopDao.findByUuid(shop.getUuid());
        shop.setStatus(Shop.Status.NO);
        shopDao.save(shop);
        return RetResponse.makeOKRsp();
    }
    @OperLog("规格删除")
    @RequestMapping("DelSpec")
    public RetResult DelSpec(@RequestBody ShopSpec shopSpec){
        shopSpec=shopSpecDao.findByUuid(shopSpec.getUuid());
        shopSpec.setStatus(ShopSpec.Status.NO);
        shopSpecDao.save(shopSpec);
        return RetResponse.makeOKRsp();
    }
    @RequestMapping("ShopList")
    public RetResult ShopList(@RequestBody JSONObject jsonObject){
        Shop entity = (Shop) BeanToJson.jsonTobean(jsonObject.getJSONObject("common").toString(), Shop.class);
        int page = Integer.parseInt(jsonObject.getString("page"))-1;
        int size = Integer.parseInt(jsonObject.getString("limit"));
        Pageable pageable=null;
        if(jsonObject.has("sort")){
            if(jsonObject.getJSONObject("sort").has("money")){
                if(jsonObject.getJSONObject("sort").getString("money").equals("DESC")){
                    pageable= PageRequest.of(page, size, Sort.Direction.DESC, "viewMoney");
                }else{
                    pageable= PageRequest.of(page, size, Sort.Direction.ASC, "viewMoney");
                }
            }
        }else{
            pageable = PageRequest.of(page, size, Sort.Direction.DESC, "modifiedTime");
        }
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains());
        entity.setStatus(Shop.Status.ING);
        Example<Shop> example = Example.of(entity,matcher);
        Page<Shop> userlist = shopDao.findAll(example,pageable);
        List<Shop> lk = userlist.getContent();
        for(Shop rl:lk){
            List<ShopSpec> specs = shopSpecDao.findByShopAndStatus(rl, ShopSpec.Status.ING);
            if(specs.size()!=0){
                Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
                if(fspuser!=null){
                    fspuser = usersDao.findByUuid(fspuser.getUuid());
                    if(fspuser.getType().equals(Users.Type.USER)){
                        for(ShopSpec sp:specs){
                            CityShop cityShop = cityShopDao.findByShopSpecAndCity(sp,cityDao.findByCityLike(fspuser.getAddress()));
                            if(cityShop!=null){
                                sp.setPrice(cityShop.getMoney());
                            }
                        }
                    }
                }
                rl.setViewMoney(specs.get(0).getPrice());
            }
        }
        return RetResponse.makeRsp(0, "成功", lk, (int) userlist.getTotalElements());
    }
    @OperLog("特殊价格设置")
    @RequestMapping("saveCitySpec")
    public RetResult saveCitySpec(@RequestBody CityShop cityShop){
        try {
            cityShopDao.save(cityShop);
            return RetResponse.makeOKRsp();
        }catch (Exception e){
            return RetResponse.makeErrRsp("当前城市已有设置，请修改");
        }
    }
    @RequestMapping("GetSpecCity")
    public RetResult GetSpecCity(@RequestBody CityShop cityShop){
        return RetResponse.makeOKRsp(cityShopDao.findByUuid(cityShop.getUuid()));
    }
}
